import { plainToClass, plainToInstance } from "class-transformer";
import StudentPaperDao from "../dao/StudentPaperDao";
import StudentPaperEntity from "../entities/StudentPaperEntity";
import ResultHelper from "../utils/ResultHelper";
import TestPaperDao from "../dao/TestPaperDao";
import { isTemplateExpression } from "typescript";
import { resourceUsage } from "process";

export default class StudentPaperService {

  static async create(data: any) {
    const StudnetPaper = plainToInstance(StudentPaperEntity, data)
    const errs = await StudnetPaper.validateThie()
    if (errs.length !== 0) {
      return ResultHelper.error(errs)
    }

    const result = await StudentPaperDao.create(StudnetPaper)

    return ResultHelper.success(result, '提交成功')
  }

  // 统计试卷考生数量
  static async statiTest() {
    // 先获取所有的试卷
    const { data } = await TestPaperDao.findByPage()

    const testIds = data.map((item) => {
      // @ts-ignore
      return item.id
    })

    const promis = []
    for (const id of testIds) {
      const p = StudentPaperDao.findExaminationCountById(id)
      promis.push(p)
    }

    let arr = await Promise.all(promis)



    const result = data.map((item) => {
      // @ts-ignore
      const id = item.id
      for (const it of arr) {
        if (id === it.id) {
          return {
            id,
            // @ts-ignore
            title: item.title,
            count: it.count
          }
        }
      }

    })

    return ResultHelper.success(result)
  }

}